package checker

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sort"

	"gitee.com/StarCitizen_CN/logger"
	"gitee.com/StarCitizen_CN/stargox/pkg/fstools"
)

func ScanL10nFilesMD5(dirPath string) (i10nFiles []L10nFile, err error) {
	files, err := fstools.ScanTree(dirPath + "\\" + targetPart0)
	if err != nil {
		logger.Err(err)
		return
	}
	files1, err := fstools.ScanTree(dirPath + "\\" + targetPart1)
	if err != nil {
		logger.Err(err)
		return
	}

	files = append(files, files1...)

	i10nFiles = []L10nFile{}
	ch := make(chan *L10nFile)

	for _, path := range files {
		go check(path, ch)
	}

	for range files {
		i10nF := <-ch

		if i10nF == nil {
			err = fmt.Errorf("扫描汉化资源出错，请查看程序目录的log。")
			return
		}

		i10nFiles = append(i10nFiles, *i10nF)
	}
	close(ch)

	return
}

func SumPackMd5(md5List []string) string {
	sort.Strings(md5List)

	var filesMd5Buf bytes.Buffer
	for i, md5 := range md5List {
		if i != 0 {
			filesMd5Buf.WriteString(".")
		}
		filesMd5Buf.WriteString(md5)
	}

	h := md5.New()
	h.Write(filesMd5Buf.Bytes())
	return hex.EncodeToString(h.Sum(nil))
}

func check(filePath string, ch chan *L10nFile) (i10nFile *L10nFile, err error) {

	f, err := os.Open(filePath)
	if err != nil {
		logger.Err(err)
		return
	}

	defer f.Close()

	md5hash := md5.New()
	if _, err = io.Copy(md5hash, f); err != nil {
		logger.Err(err)
		return
	}
	md5hash.Sum(nil)
	md5Str := fmt.Sprintf("%x", md5hash.Sum(nil))

	_, fileName := filepath.Split(filePath)
	fmt.Printf("%s %s\n", fileName, md5Str)

	i10nFile = &L10nFile{
		Name: fileName,
		Path: filePath,
		Md5:  md5Str,
	}

	ch <- i10nFile

	return
}
